package com.example.batch.core.transaction.compensation;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class CompensationManager {

    private final TransactionLogRepository transactionLogRepository;
    private final Map<String, CompensationHandler> compensationHandlers;
    private final TransactionTemplate transactionTemplate;
    
    @Scheduled(fixedRate = 300000) // 每5分钟执行一次
    public void processFailedTransactions() {
        List<TransactionLog> failedLogs = transactionLogRepository
            .findByStatusAndRetryCountLessThan(FAILED, maxRetries);
            
        for (TransactionLog log : failedLogs) {
            try {
                compensate(log);
            } catch (Exception e) {
                log.error("Compensation failed for transaction: " + log.getTransactionId(), e);
                updateFailedLog(log);
            }
        }
    }
    
    public void compensate(TransactionLog log) {
        CompensationHandler handler = compensationHandlers.get(log.getTransactionType());
        if (handler == null) {
            throw new IllegalStateException("No handler found for: " + log.getTransactionType());
        }
        
        transactionTemplate.execute(status -> {
            try {
                handler.compensate(log);
                log.setStatus(COMPENSATED);
                transactionLogRepository.save(log);
                return true;
            } catch (Exception e) {
                status.setRollbackOnly();
                throw e;
            }
        });
    }
} 